package cn.edu.dgut.css.sai.security.oauth2.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.ClientsConfiguredCondition;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * OAuth2客户端配置类
 *
 * @author Sai
 * @since 1.0.5
 */
@Conditional(ClientsConfiguredCondition.class)
@ConditionalOnClass({EnableWebSecurity.class, ClientRegistration.class})
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableConfigurationProperties(SaiOAuth2ConfigProperties.class)
public final class SaiOAuth2ClientRegistrationRepositoryConfiguration {

    private final OAuth2ClientProperties properties;

    SaiOAuth2ClientRegistrationRepositoryConfiguration(OAuth2ClientProperties properties, SaiOAuth2ConfigProperties saiOAuth2ConfigProperties) {
        this.properties = properties;
        if (!saiOAuth2ConfigProperties.getAuthorizationResponseBasePath().equals("/login/oauth2/code"))
            this.properties.getRegistration().forEach((s, registration) -> registration.setRedirectUri("{baseUrl}" + saiOAuth2ConfigProperties.getAuthorizationResponseBasePath() + "/{registrationId}"));
    }

    @Bean
    public InMemoryClientRegistrationRepository clientRegistrationRepository() {
        List<ClientRegistration> registrations = new ArrayList<>(
                SaiOAuth2ClientPropertiesRegistrationAdapter
                        .getClientRegistrations(this.properties).values());
        return new InMemoryClientRegistrationRepository(registrations);
    }

}
